package com.example.myapplication.view

import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.databinding.DataBindingUtil
import com.example.myapplication.R
import com.example.myapplication.databinding.LayoutNumberComboBigBinding
import com.example.myapplication.databinding.LayoutNumberComboBinding
import com.example.myapplication.shortvideo.utils.DisplayUtils


/**
 * @author zijian.cheng
 * @date 2019/8/19
 */
class GiftNumComboLayout(context: Context?, attrs: AttributeSet?) : FrameLayout(context!!, attrs) {
    private val animatorSet = AnimatorSet()
    private var runComboBg: Boolean = false
    var binding : LayoutNumberComboBinding? = null
    init {
        binding = DataBindingUtil.bind( View.inflate(context, R.layout.layout_number_combo, this))
        val objectAnimatorX = ObjectAnimator.ofFloat(binding!!.idRootView, "scaleX", 2f, 0.5f, 1f)
        val objectAnimatorY = ObjectAnimator.ofFloat(binding!!.idRootView, "scaleY", 2f, 0.5f,  1f)
        animatorSet.duration = 250
        animatorSet.playTogether(objectAnimatorX, objectAnimatorY)
        objectAnimatorY.addUpdateListener {
            if (!runComboBg && (it.animatedValue as Float) < 1.5f) {
                runComboBg = true
            }
        }
    }

    fun numberCombo(number: Long) {
        binding!!.idNumberContent.removeAllViews()
        number.toString().forEach {
            val child = ImageView(context)
            child.scaleType = ImageView.ScaleType.FIT_XY
            val layout = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
            layout.leftMargin = -DisplayUtils.dp2px(4)
            child.layoutParams = layout
            child.setImageDrawable(getDrawable(context, getResForNumber(it.toString().toInt())))
            binding!!.idNumberContent.addView(child)
        }

        val w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        binding!!.idNumberContent.measure(w, w)
        val params = binding!!.idRootView.layoutParams
        params.width =   binding!!.idNumberContent.measuredWidth + DisplayUtils.dp2px(40)
        binding!!.idRootView.layoutParams = params

        if (animatorSet.isRunning) {
            animatorSet.cancel()
        }
        runComboBg = false
        animatorSet.start()
    }

    fun getDrawable(context: Context, resId: Int): Drawable? {
        return context.resources.getDrawable(resId)
    }

    private fun getResForNumber(number: Int): Int {
        return R.mipmap.icon_give_gift_0 + number
    }
}